<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>9-1</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        
        .red {
            height: 200px;
            background-color: red;
        }
        
        .black {
            height: 50px;
            width: 100%;
            /* 当position是fixed时，不设置width会显示不出来。
            当position是relavite时，width默认为100% */
            position: relative;
            background-color: black;
            top: 0;
        }
        
        .white {
            height: 500px;
            width: 1500px;
            background-color: pink;
        }
    </style>
</head>

<body>
    <div class="red"></div>
    <div class="black"></div>
    <div class="white"></div>
    <script>
        var black = document.querySelector('.black');
        document.addEventListener('scroll', function() {
            if (window.pageYOffset > 200) {
                /* 页面滚动，时间源是ducument */
                black.style.position = 'fixed';
                /*  position 也是样式 */

            } else {
                black.style.position = 'relative';
            }
        })
    </script>
</body>

</html>